#include "Draw.h"

SDL_Surface *Draw::screen = NULL;

	TTF_Font* Draw::font = TTF_OpenFont( "DroidSerif-Regular.ttf", 16 );
	SDL_Color * Draw::textColor = new SDL_Color();
Draw::Draw(void)
{
}


Draw::~Draw(void)
{
}

void Draw::putTextAt(int x, int y, std::string text)
{	
	if(screen!=NULL)
	{
	SDL_Color textColor = *new SDL_Color();
	textColor.r = 150;
	textColor.g = 150;
	textColor.b = 150;
	if(Draw::font==NULL)
	{
		Draw::font = TTF_OpenFont( "DroidSerif-Regular.ttf", 16 );
	}
	//SDL_Surface *message = TTF_RenderText_Solid(Draw::font, text.c_str(), textColor);
	//if(message!=NULL)
    Draw::apply_surface( x, y, TTF_RenderText_Solid(Draw::font, text.c_str(), textColor), screen );

	//SDL_FreeSurface( message );
	
	delete(&textColor);
	}
	
}

void Draw::putTextAt(int x, int y, std::string text, SDL_Surface* surface)
{
	if(surface!=NULL)
	{
		Draw::textColor->r = 150;
	Draw::textColor->g = 150;
	Draw::textColor->b = 150;
	if(Draw::font==NULL)
	{
		Draw::font = TTF_OpenFont( "DroidSerif-Regular.ttf", 16 );
	}
	SDL_Surface *message = TTF_RenderText_Solid(Draw::font, text.c_str(), *Draw::textColor);
	if(message!=NULL)
    Draw::apply_surface( x, y, message, surface );

	SDL_FreeSurface( message );
	
	}

}

SDL_Surface* Draw::load_image(std::string const& path, bool alpha) {
	::SDL_Surface *result = ::IMG_Load(path.c_str());

	if (result) {

		::SDL_Surface *tmp;
		if (alpha) {
			tmp = ::SDL_DisplayFormatAlpha(result);

		}
		else {
			tmp = ::SDL_DisplayFormat(result);

		}
		if (tmp) {
			::SDL_FreeSurface(result);
			result = tmp;

		}
		else {
			// signal the error, return the original, unconverted
			// surface

		}
	}
	else {

	}
	return result;
}
void Draw::apply_surface(const int x, const int y,  SDL_Surface* source, SDL_Surface* destination,  SDL_Rect* clip  )//clip is the clip taken from the SOURCE. it has x,y,w, and h.
{
	//Holds offsets
	SDL_Rect offset;

	//Get offsets
	offset.x = x;
	offset.y = y;
	
	
        
	SDL_BlitSurface( source, clip, destination, &offset );
}

void Draw::apply_surface(const int x, const int y,  SDL_Surface* source,  SDL_Rect* clip  )//clip is the clip taken from the SOURCE. it has x,y,w, and h.
{
	Draw::apply_surface(x,y,source,screen, clip);
}

double Draw::distanceFormula(int x1, int y1, int x2, int y2)
{
	//sqrt( (float) (x1-x2)^2 + (y1-y2)^2)
	 return 
	 std::sqrt( (double)((x1-x2)^2 + (y1-y2)^2));
 
}

void Draw::setColor(SDL_Surface *surface, SDL_Color color) {
        Uint32 *pixels = (Uint32 *) surface->pixels;            // Get the pixels from the Surface
		
        // Iterrate through the pixels and chagne the color
        for (int i = 0; i * surface->w *surface->h; i++) {
			

                pixels[i] = SDL_MapRGB(surface->format, color.r, color.b, color.g);
        }
    }